/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.result;

import java.util.*;
import java.io.*;
import java.net.*;
import javax.net.*;
import javax.net.ssl.*;
import java.util.concurrent.Semaphore;

import nfse.*;

public class ResultMarshall extends Thread implements Comparable<ResultMarshall> {
    private DatabaseResult databaseResult = null;
    
    private final Semaphore available = new Semaphore(1, true);

    private int pending = 0;

    private Vector<Record> records = null;

    private SocketResult socketResult = null;

    private MarshalledResult marshalledResult = null;

    private int recordCount = 0;

    private int MAX_RECORDS = 5000;

    private boolean connected = true;

    public int queryID;

    public final int SLEEP_MS = 1000;

    private int expected = 0;

    public String toString() {
        String temp = "QID=" + queryID + ", connected=" + connected + ", numRecords=" + getNumRecords() + ", result=";
        if (databaseResult != null)
            temp += databaseResult.toXML();
        else if (socketResult != null)
            temp += socketResult.toXML();
        else if (marshalledResult != null)
            temp += marshalledResult.toXML();
        return temp;
    }

    public ResultMarshall(Result result, int queryID) {
        this.queryID = queryID;
        records = new Vector<Record>();
        try {
            socketResult = (SocketResult) result;
        } catch (Exception E) {
            try {
                databaseResult = (DatabaseResult) result;
            } catch (ClassCastException cce2) {
                marshalledResult = (MarshalledResult) result;
            }
        }
    }

    public boolean isConnected() {
        return connected;
    }

    public void setPending(int pending) throws InterruptedException {
    	available.acquire();
        this.pending = pending;
        available.release();
    }

    public void addProducer()  throws InterruptedException {
    	available.acquire();
        pending++;
        available.release();
    }

    public void addExpected(int expected)  throws InterruptedException {
    	available.acquire();
        this.expected += expected;
        available.release();
    }

    public int addRecord(Record record)  throws InterruptedException {
    	available.acquire();
    	if (!connected) {
    		available.release();
            return -2;
        } else if (recordCount < MAX_RECORDS) {
            records.addElement(record);
            recordCount++;
        } else {
        	available.release();
            return -1;
        }
    	available.release();
        return 0;
    }

    private Record removeRecord()  throws InterruptedException {
    	available.acquire();
    	if (records.size() > 0) {
            recordCount--;
            available.release();
            return (Record) records.remove(0);
        }
    	available.release();
        return null;
    }

    public int compareTo(ResultMarshall rm) {
        try {
            if ((rm.marshalledResult != null) && (marshalledResult == null))
                return -1;
            if ((rm.marshalledResult == null) && (marshalledResult != null))
                return -1;
            if ((rm.marshalledResult == null) && (marshalledResult == null))
                return -1;
            if (rm.marshalledResult.compareTo(this.marshalledResult) != 0)
                return -1;

            if ((rm.databaseResult != null) && (databaseResult == null))
                return -1;
            if ((rm.databaseResult == null) && (databaseResult != null))
                return -1;
            if ((rm.databaseResult == null) && (databaseResult == null)) {

            } else if (rm.databaseResult.compareTo(this.databaseResult) != 0)
                return -1;

            if ((rm.socketResult != null) && (socketResult == null))
                return -1;
            if ((rm.socketResult == null) && (socketResult != null))
                return -1;
            if ((rm.socketResult == null) && (socketResult == null)) {

            } else if (rm.socketResult.compareTo(this.socketResult) != 0)
                return -1;

            if (rm.pending != pending)
                return -1;

        } catch (ClassCastException cce) {
            return -1;
        }
        return 0;
    }

    private int getNumRecords() {
        return records.size();
    }

    private void processDatabaseResult() {

    }

    private void processMarshalledResult() {
        Socket resultSocket = null;
        try {
            SocketFactory sf = SocketFactory.getDefault();
            resultSocket = sf.createSocket(marshalledResult.host, marshalledResult.port);
            resultSocket.setReceiveBufferSize(NetFSE.SOCKET_RECV_SIZE);
            resultSocket.setSendBufferSize(NetFSE.SOCKET_SEND_SIZE);
            // System.out.println("BUFFER SIZES: " +
            // resultSocket.getReceiveBufferSize() + ", " +
            // resultSocket.getSendBufferSize());
            DataOutputStream resultOut = new DataOutputStream(resultSocket.getOutputStream());
            DataInputStream resultIn = new DataInputStream(resultSocket.getInputStream());

            // System.out.println("ResultMarshall: returning results for query
            // #" + marshalledResult.queryID);
            resultOut.writeInt(marshalledResult.queryID);
            resultOut.writeInt(NetFSE.RESULT_SERVER_FLAG_DONE);
            int count = 0;

            Record record = null;
            byte[] bytes = null;
            while (((count < expected) || (pending > 0)) && (resultSocket.isConnected())) {
                if (records.size() == 0)
                    Thread.sleep(SLEEP_MS);
                while (records.size() > 0) {
                    record = this.removeRecord();
                    try {
                        bytes = record.record.getBytes();
                        resultOut.writeInt(record.type);
                        resultOut.writeInt(record.sensor);
                        resultOut.writeInt(bytes.length);
                        if (bytes.length > 0)
                            resultOut.write(bytes);
                        // System.out.println("Wrote to " +
                        // marshalledResult.host + ":" + marshalledResult.port +
                        // "'" + record.record + "'");
                    } catch (IOException ioe) {
                        // ioe.printStackTrace();
                        connected = false;
                    }
                    count++;
                }

            }

            try {
                resultOut.writeInt(-100);
                resultOut.writeInt(count);
                resultIn.readInt();
                resultSocket.close();
            } catch (Exception e) {
                // no op
            }
        } catch (Exception E) {
            E.printStackTrace();
        }
    }

    private void processSocketResult() {
        Socket resultSocket = null;
        try {
            if ((socketResult.host == null) || (socketResult.host.equals("null")) || (socketResult.host.length() == 0))
                socketResult.host = "localhost";
            System.out.println(this.queryID + " processSocketResult: Connecting to " + socketResult.host + ":"
                    + socketResult.port + "!");

            SocketFactory sf = null;
            if (NetFSE.USE_SSL_RESULT)
                sf = SSLSocketFactory.getDefault();
            else
                sf = SocketFactory.getDefault();
            resultSocket = sf.createSocket(socketResult.host, socketResult.port);
            resultSocket.setReceiveBufferSize(NetFSE.SOCKET_RECV_SIZE);
            resultSocket.setSendBufferSize(NetFSE.SOCKET_SEND_SIZE);
            DataOutputStream resultOut = new DataOutputStream(resultSocket.getOutputStream());
            // DataInputStream resultIn = new
            // DataInputStream(resultSocket.getInputStream());

            /*
             * System.out.println( this.queryID + " processSocketResult:
             * Connected to " + socketResult.host + ":" + socketResult.port +
             * "!");
             */
            int count = 0;
            Record record = null;
            byte[] bytes = null;
            // while (((pending > 0) || (totalRecords > 0)) &&
            // (resultSocket.isConnected())) {
            while (((count < expected) || (pending > 0)) && (resultSocket.isConnected())) {
                if (records.size() == 0)
                    Thread.sleep(SLEEP_MS);
                while (records.size() > 0) {
                    record = this.removeRecord();
                    try {
                        bytes = record.record.getBytes();
                        resultOut.writeInt(record.type);
                        resultOut.writeInt(record.sensor);
                        resultOut.writeInt(bytes.length);
                        if (bytes.length > 0)
                            resultOut.write(bytes);
                        // System.out.println("Wrote to " + socketResult.host +
                        // ":" + socketResult.port + ", '" + record.record +
                        // "'");
                    } catch (IOException ioe) {
                        connected = false;
                    }
                    count++;
                }
            }
            try {
                resultOut.writeInt(-100);
                resultOut.writeInt(count);
            } catch (Exception e) {
                // no op
            }
            DataInputStream resultIn = new DataInputStream(resultSocket.getInputStream());
            int reply = -1;
            try {
                reply = resultIn.readInt();
            } catch (Exception e) {
                // no op
            }
            System.out.println("ResultMarshall: finished " + queryID + ", records=" + count + ", reply=" + reply);
            resultSocket.close();
        } catch (Exception E) {
            E.printStackTrace();
        }
    }

    public synchronized void removeProducer() throws InterruptedException {
    	available.acquire();
    	pending--;
        available.release();
    }

    public void run() {
        if (socketResult != null) {
            processSocketResult();
        } else if (marshalledResult != null) {
            processMarshalledResult();
        } else if (databaseResult != null) {
            processDatabaseResult();
        }
    }

}
